package me.leiusual.sharing.ui.store

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import dagger.android.support.DaggerFragment
import kotlinx.android.synthetic.main.fragment_store_area.*
import me.leiusual.sharing.R
import me.leiusual.sharing.ui.store.adapter.StoreAreaAdapter
import timber.log.Timber
import javax.inject.Inject

/**
 * author: leiusual
 * create on: 2019-07-25
 * description:
 */
class StoreAreaFragment : DaggerFragment() {

  companion object {
    private const val STORE_ID = "store_id"
    private const val STORE_AREA_ID = "store_area_id"
    private const val CATEGORY_ID = "category_id"

    fun newInstance(storeId: Long, storeAreaId: Long, categoryId: Long): StoreAreaFragment {
      return StoreAreaFragment().apply {
        val args = Bundle()
        args.putLong(STORE_ID, storeId)
        args.putLong(STORE_AREA_ID, storeAreaId)
        args.putLong(CATEGORY_ID, categoryId)
        arguments = args
      }
    }
  }

  @Inject
  lateinit var factory: ViewModelProvider.Factory

  private val viewModel: StoreAreaViewModel by viewModels { factory }

  override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    return inflater.inflate(R.layout.fragment_store_area, container, false)
  }

  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    recycler_view.adapter = StoreAreaAdapter {
      Timber.v("点击：%s", it)

      // 导航到商品详情
      val action = StoreHomeFragmentDirections.actionStoreHomeFragmentToProductDetailFragment(it.miaId, it.curStoreId)
      findNavController().navigate(action)
    }

    observeData()
    doStoreProductQuery()
  }

  fun updateCategoryId(categoryId: Long) {
    arguments?.putLong(CATEGORY_ID, categoryId)
    doStoreProductQuery()
  }

  private fun observeData() {
    viewModel.storeProductQuery.observe(viewLifecycleOwner, Observer {
      Timber.v("storeProductQuery = %s", it)

      val adapter = recycler_view.adapter as StoreAreaAdapter
      adapter.submitList(it)
    })
  }

  private fun doStoreProductQuery() {
    val storeId = arguments?.getLong(STORE_ID) ?: viewModel.store.currentStoreId
    val storeAreaId = arguments?.getLong(STORE_AREA_ID) ?: 0
    val categoryId = arguments?.getLong(CATEGORY_ID) ?: 0
    viewModel.storeProductQuery(storeId, storeAreaId, categoryId)
  }
}